define(['app', 'pagination', 'datetime', 'laydate', 'filesaver', 'autocomplete', 'fileupload','floatlayer'], function(app) {
    'use strict';
    /**
     * 风险管理前端控制器
     *
     * @author ZhangYe<banfg56@gmail.com>
     * @dete   02/19/2017
     */
    app.controller('Risk', function($scope, dataFactoryCRM, $q, Upload) {
            $scope.riskpage = { pageAll: 1, pageNow: 1, pageSize: $scope.psize, k: 55 };
            $scope.add_data = { level: 1, is_repeat: false };
            $scope.state = { rcode: false, msg: {} };
            $scope.add_last_risk = {};
            $scope.pageOption = {};
            $scope.search_param = { userphone: '', sales: '', start_time: '', end_time: '', status: 0 };
            $scope.risklist = [];
            $scope.customer = [{}];


            $scope.getPageOption = function() {
                var _url = 'risk/options'
                dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
                    if (_d.rcode)
                        $scope.pageOption = _d.data;
                    else
                        $scope.riskpage.pageAll = 0;
                });
            };

            /**获取客户信息 */
            $scope.getCustomer = function(newValue) {
                var _url = 'risk/getCustomers?customer=' + newValue;
                dataFactoryCRM.getDataByAPI(_url).then(function(response) {
                    if (response.rcode) {
                        $scope.customer = response.data;
                    } else {
                        $scope.customer = [{}];
                    }
                });
            };

            /**自动补全选择 */
            $scope.selectCustomer = function(selected) {
                if (selected) {
                    $scope.add_data.customer_id = selected.originalObject.customer_id;
                    $scope.add_data.customer_name = selected.originalObject.nickname;
                    $scope.add_data.sales_id = selected.originalObject.sales_id;
                    $scope.add_data.sales_name = selected.originalObject.sales_name;
                    $scope.add_data.sales_manager = selected.originalObject.sales_manager;
                    $scope.add_data.manager_name = selected.originalObject.manager;
                    $scope.add_data.sales_company = selected.originalObject.sales_sub_company;

                    $('#add_data_customer_name1').val($scope.add_data.customer_name);
                    $('#add_data_customer_name3').val($scope.add_data.customer_name);
                }
            };
       
            /**获取列表页 */
            $scope.getRiskList = function() {
                var listParam = $scope.search_param;
                listParam['psize'] = $scope.riskpage.pageSize;
                listParam['p'] = $scope.riskpage.pageNow;
                var _url = 'risk/index?' + $.param(listParam);
                $scope.$emit('BUSY');
                dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
                    $scope.$emit('NOTBUSY');
                    if (_d.rcode) {
                        $scope.riskpage.pageSize = _d.psize;
                        $scope.riskpage.pageAll = _d.pall;
                        $scope.riskpage.pageNow = _d.p;
                        $scope.risklist = _d.data;
                        setTimeout(function() {
                            $('.starlist').rating({ interactive: false });
                        }, 300);
                    } else
                        $scope.riskpage.pageAll = 0;
                });
            };


            /**列表页检索 */
            $scope.search = function() {
                // $scope.search_param.status = -1;
                $scope.getRiskList();
            };

             //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
            window.loadClientCacheToScope($scope, function() {
                $scope.getRiskList();
            });

            /**清空搜索 */
            $scope.clearSearch = function() {
                $scope.search_param = {};
            };

            /**添加风险 */
            $scope.add_popup = function() {

                /**添加成功 */
                function addSuccess() {
                    setTimeout(function() {
                        $('.modal1').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal1').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**添加失败 */
                function addFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal2').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal2').modal('hide')
                        }, 3000)
                    }, 100);
                }

                function initAddOptions() {
                    $('.popup.add.form input').val('');
                    $scope.add_data = {
                        level: 1,
                        is_repeat: false,
                        customer_name: '',
                        customer_phone: '',
                        sales_name: '',
                        sales_manager: '',
                        description: '',
                        feedback: '',
                        customer_id: '',
                        sales_company: null,
                    };
                    $('.add-rating').rating('set rating', 1);
                }

                function add(data) {
                    $scope.$emit('BUSY');
                    $scope.busy = dataFactoryCRM.postDataByAPI('risk/add', data)
                        .then(function(d) {
                            if (d && d.rcode) {
                                addSuccess();
                                initAddOptions();
                                $scope.getRiskList();
                                return true;
                            } else {
                                $scope.$emit("NOTBUSY");
                                addFail();
                                return false;
                            }
                        });
                }

                $('.add.form').form('clear');
                $scope.$broadcast('angucomplete-alt:clearInput');
                $('.ui.add').modal({
                    observeChanges: true,
                    closable:false,
                    onApprove: function() {
                        if ($('.add.form').form('is valid')) {
                            add($scope.add_data);
                        } else {
                            return false;
                        }
                    }
                }).modal('show');
            };

            /************************编辑******************** */
            /**风险编辑 */
            $scope.edit_popup = function(v) {

                /**更新成功 */
                function updateSuccess() {
                    setTimeout(function() {
                        $('.modal4').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal4').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**更新失败 */
                function updateFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal5').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal5').modal('hide')
                        }, 3000)
                    }, 1000);
                }

                function risk_edit(data) {
                    $scope.$emit('BUSY');
                    $scope.busy = dataFactoryCRM.postDataByAPI('risk/edit', data)
                        .then(function(d) {
                            if (d && d.rcode) {
                                updateSuccess();
                                $scope.getRiskList();
                            } else {
                                updateFail();
                                $scope.$emit('NOTBUSY');
                            }
                        });
                }

                dataFactoryCRM.getDataByAPI('risk/confirm?id=' + v.risk_id).then(function(d) {
                    if (d && d.rcode) {
                        $scope.add_data = d.data;
                        $('.add-rating').rating('set rating', $scope.add_data.level);
                        $('#add_data_customer_name4_value').val($scope.add_data.customer_name);
                        $('#add_data_customer_name3').val($scope.add_data.customer_name);
                        $scope.add_data.is_repeat = $scope.add_data.is_repeat == '1' ? true : false;
                        setTimeout(function() {
                            $('.ui.more.dropdown').dropdown();
                            $('.starconfirm').rating({ interactive: false });
                        }, 300);
                        $('.ui.edit.modal').modal({
                            observeChanges: true,
                            closable:false,
                            onApprove: function() {
                                if ($('.update.form').form('is valid')) {
                                    risk_edit($scope.add_data);
                                } else {
                                    return false;
                                }
                            }
                        }).modal('show');
                    } else {
                        alert(d.msg);
                    }
                });
            };

            $scope.saleName = function() {
                if ($scope.add_data.sales_name && !$scope.add_data.sales_id) $scope.add_data.sales_name = '';
            };

            $scope.saleManager = function() {
                if ($scope.add_data.manager_name && !$scope.add_data.sales_manager) $scope.add_data.manager_name = '';
            };

            /************************编辑******************** */

            /**风险确认 */
            $scope.confirm_popup = function(v) {

                /**更新成功 */
                function updateSuccess() {
                    setTimeout(function() {
                        $('.modal4').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal4').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**更新失败 */
                function updateFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal5').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal5').modal('hide')
                        }, 3000)
                    }, 1000);
                }

                function risk_confirm(data) {
                    $scope.$emit('BUSY');
                    $scope.busy = dataFactoryCRM.postDataByAPI('risk/confirm', data)
                        .then(function(d) {
                            if (d && d.rcode) {
                                updateSuccess();
                                $scope.confirm = { id: 0, confirm: '' };
                                $scope.getRiskList();
                            } else {
                                $scope.$emit('NOTBUSY');
                                updateFail();
                            }
                        });
                }

                if (v.status != 0) {
                    $scope.track_popup(v);
                    return true;
                }

                dataFactoryCRM.getDataByAPI('risk/confirm?id=' + v.risk_id).then(function(d) {
                    if (d && d.rcode) {
                        $scope.risk_detail = d.data;
                        setTimeout(function() {
                            $('.starconfirm').rating({ interactive: false });
                            $('.ui.more.dropdown').dropdown();
                        }, 100);
                        $('.ui.confirm.modal').modal({
                            observeChanges: true,
                             closable:false,
                            onApprove: function() {
                                if ($('.confirm.form').form('is valid')) {
                                    risk_confirm($scope.risk_detail);
                                } else {
                                    return false;
                                }
                            }
                        }).modal('show');
                    } else {
                        alert(d.msg);
                    }
                });
            };

            /**风险删除 */
            $scope.remove_popup = function(v) {
                function remove(d) {
                    $scope.$emit('BUSY');
                    $scope.busy = dataFactoryCRM.postDataByAPI('risk/delete', { id: d.risk_id })
                        .then(function(d) {
                            if (d && d.rcode) {
                                $scope.getRiskList();
                                $scope.delete_data = {};
                            } else {
                                $scope.$emit('NOTBUSY');
                            }
                        });
                }

                $scope.delete_data = v;
                $('.ui .modal3').modal({
                    observeChanges: true,
                    onApprove: function() {
                        remove($scope.delete_data);
                        return true;
                    }
                }).modal('show');


                // $scope.delete_data = v;
                // $('.small.remove.modal')
                //     .modal({
                //         onApprove: function() {
                //             remove($scope.delete_data);
                //         }
                //     })
                //     .modal('setting', 'closable', false)
                //     .modal('show');
            };

            /**风险关闭 */
            $scope.track_close = function(v, b) {

                /**更新成功 */
                function updateSuccess() {
                    setTimeout(function() {
                        $('.modal4').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal4').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**更新失败 */
                function updateFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal5').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal5').modal('hide')
                        }, 3000)
                    }, 1000);
                }

                var data = { id: v.risk_id, force: b };
                $scope.busy = dataFactoryCRM.postDataByAPI('risk/close', data)
                    .then(function(d) {
                        if (d && d.rcode) {
                            $scope.getRiskList();
                            updateSuccess();
                        } else {
                            updateFail();
                        }
                    });
            };

            /**风险追踪 */
            $scope.track_popup = function(v) {
                /**更新成功 */
                function updateSuccess() {
                    setTimeout(function() {
                        $('.modal4').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal4').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**更新失败 */
                function updateFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal5').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal5').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**提交更新 */
                function risk_confirm(data) {
                    $scope.$emit('BUSY');
                    $scope.busy = dataFactoryCRM.postDataByAPI('risk/track_new', data)
                        .then(function(d) {
                            if (d && d.rcode) {
                                updateSuccess();
                                $scope.track_data = {};
                                $scope.getRiskList();
                            } else {
                                $scope.$emit('NOTBUSY');
                                updateFail();
                            }
                        });
                }

                dataFactoryCRM.getDataByAPI('risk/track?id=' + v.risk_id).then(function(d) {
                    if (d && d.rcode) {
                        $scope.track = { risk_id: d.risk.risk_id };
                        $scope.track_data = d.risk;
                        $scope.track_list = d.track;
                        $scope.track_data.reply = '';
                        $scope.track_data.reply_confirm = '';
                        $('.add-rating').rating('set rating', $scope.track_data.level);
                        $scope.track_data.is_repeat = $scope.track_data.is_repeat == '1' ? true : false;
                        setTimeout(function() {
                            $('.startrack').rating({ interactive: false });
                            $('.ui.more.dropdown').dropdown();
                        }, 100);
                        $('.ui.track.modal').modal({
                            observeChanges: true,
                            closable:false,
                            onApprove: function() {
                                if ($('.track.form').form('is valid')) {
                                    risk_confirm($scope.track_data);
                                } else {
                                    return false;
                                }
                            }
                        }).modal('show');
                    } else {
                        alert(d.msg);
                    }
                });
            };

            // /**保存追踪 */
            // $scope.saveTrack = function() {
            //     if ($('.track.form').form('is valid')) {
            //         $scope.busy = dataFactoryCRM.postDataByAPI('risk/track', $scope.track)
            //             .then(function(d) {
            //                 if (d && d.rcode) {
            //                     $scope.track.reply = '';
            //                     $scope.track.reply_confirm = '';
            //                     $scope.track_list = d.data;
            //                 }
            //             });
            //     } else {
            //         return false;
            //     }
            // };

            /**风险挂起 */
            $scope.track_hangup = function(v, b) {

                /**更新成功 */
                function updateSuccess() {
                    setTimeout(function() {
                        $('.modal4').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal4').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**更新失败 */
                function updateFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal5').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal5').modal('hide')
                        }, 3000)
                    }, 1000);
                }

                var data = { id: v.risk_id, force: b };
                $scope.busy = dataFactoryCRM.postDataByAPI('risk/hangup', data)
                    .then(function(d) {
                        if (d && d.rcode) {
                            $scope.getRiskList();
                            updateSuccess();
                        } else {
                            updateFail();
                        }
                    });
            };

            /**风险查看 */
            $scope.view_popup = function(v) {
                $scope.track_data = {};
                $scope.track_list = {};
                dataFactoryCRM.getDataByAPI('risk/track?id=' + v.risk_id).then(function(d) {
                    if (d && d.rcode) {
                        $scope.track = { risk_id: d.risk.risk_id };
                        $scope.track_data = d.risk;
                        $scope.track_list = d.track;
                        $('.see.rating').rating('set rating', $scope.track_data.level);
                        setTimeout(function() {
                            $('.startrack').rating({ interactive: false });
                        }, 100);
                        $('.ui.view.modal').modal({
                             closable:false,
                            observeChanges: true,
                        }).modal('show');
                    } else {
                        alert(d.msg);
                    }
                });
            };

            /**风险导入 */
            $scope.riskImport = function() {
                // $scope.$emit("BUSY");
                var file = $scope.file;
                Upload.upload({
                    //服务端接收
                    url: '/Admin/Risk/riskImport',
                    //上传的同时带的参数
                    data: { 'p': 1 },
                    data: {},
                    //上传的文件
                    file: file
                }).progress(function(evt) {
                    //进度条
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                }).success(function(data, status, headers, config) {
                    //上传成功
                    $scope.state.rcode = data.rcode == 1 ? true : false;
                    $scope.state.msg = data.rcode == 1 ? {} : data.data;
                    $scope.file = '';
                    $scope.getRiskList();
                    if ($scope.state.rcode) alert('导入成功!');
                    if (!$scope.state.rcode) $('.ui.small.import').modal('show');
                    $scope.$emit("NOTBUSY");
                }).error(function(data, status, headers, config) {
                    //上传失败
                    $scope.$emit("NOTBUSY");
                });
            };

            /*风险导出 */
            $scope.riskExport = function() {
                var listParam = $scope.search_param;
                var _url = 'risk/riskExport?' + $.param(listParam);
                dataFactoryCRM.getDataByAPIS(_url).then(function(response) {
                    var blob = new Blob([response], {
                        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    });
                    saveAs(blob, '风险数据记录表' + '.xls');
                });
            };

            /**加载用户 */
            $scope.load_user = function(_name) {
                var deferred = $q.defer();
                if (_name) {
                    $scope.busy = dataFactoryCRM.postDataByAPI('user/searchByName', { 'name': _name })
                        .then(function(d) {
                            deferred.resolve(d);
                        });
                } else
                    deferred.reject('参数提交错误');
                return deferred.promise;
            };

            /**加载客户 */
            $scope.load_customer = function(_name) {
                var deferred = $q.defer();
                if (_name) {
                    $scope.busy = dataFactoryCRM.postDataByAPI('user/searchCustomerName', { 'name': _name })
                        .then(function(d) {
                            deferred.resolve(d);
                        });
                } else
                    deferred.reject('参数提交错误');
                return deferred.promise;
            };

            /**进入界面自动运行 */
            $scope.auto = function() {
                $scope.getCustomer();
                $scope.getRiskList();
                $scope.getPageOption();
            };
            $scope.auto();

            /**导入文件监控 */
            $scope.$watch('file', function(newValue, oldValue) {
                if (newValue && newValue != oldValue) {
                    $scope.riskImport();
                }
            });

            /*监视搜索条件变化*/
            $scope.$watch('search_param.status', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                $scope.riskpage.pageNow = 1;
                $scope.getRiskList();
            }, true);

            /* 根据员工姓名自动匹配后台员工 */
            $scope.$watch('add_data.sales_name', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                $scope.load_user(newValue).then(function(d) {
                    if (d && 1 == d.rcode) {
                        $scope.add_data.sales_id = d.data.user_id;
                        $scope.add_data.sales_sector = d.data.sector_id;
                        $scope.add_data.sales_name = d.data.nickname;
                    } else if (d && 0 == d.rcode) {
                        $scope.add_data.sales_id = '';
                        $scope.add_data.sales_sector = '';
                        $scope.add_data.sales_name = '';
                    } else if (d && 2 == d.rcode) {
                        $scope.add_data.sales_id = '';
                        $scope.add_data.sales_sector = '';
                    }
                });
            }, true);

            /**自动匹配团队经理 */
            $scope.$watch('add_data.manager_name', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                $scope.load_user(newValue).then(function(d) {
                    if (d && 1 == d.rcode) {
                        $scope.add_data.sales_manager = d.data.user_id;
                        $scope.add_data.manager_name = d.data.nickname;
                    } else if (d && 0 == d.rcode) {
                        $scope.add_data.manager_name = '';
                        $scope.add_data.sales_manager = '';
                    } else if (d && 2 == d.rcode) {
                        $scope.add_data.sales_manager = '';
                    }
                });
            }, true);

            /**自动匹配客户信息 */
            $scope.$watch('add_data.customer_name', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                $scope.load_customer(newValue).then(function(d) {
                    if (d && 1 == d.rcode) {
                        $scope.add_data.customer_id = d.data.customer_id;
                        $scope.add_data.customer_name = d.data.nickname;
                        $scope.add_data.customer_phone = d.data.phone;
                        $scope.add_data.sales_id = d.data.sales_id;
                        $scope.add_data.sales_name = d.data.sales_name;
                        $scope.add_data.sales_sector = d.data.sales_sector;
                        $scope.add_data.sales_manager = d.data.sales_manager;
                        $scope.add_data.manager_name = d.data.manager_name;
                        $scope.add_data.sales_company = d.data.sales_company;
                    } else if (d && 0 == d.rcode) {
                        $scope.add_data.customer_id = '';
                    }
                    setTimeout(function() {
                        $('.ui.more.dropdown').dropdown();
                        $('#add_data_customer_phone1').trigger('blur');
                        $('#add_data_sales_name1').trigger('blur');
                        $('#add_data_manager_name1').trigger('blur');
                        $('#add_data_sales_company1').trigger('blur');
                    }, 50);
                });
            }, true);

            /**自动补全多输入 */
            $scope.customerInputChanged = function($item) {
                $scope.checkCustomer = $item;
            };

            $scope.$watch('checkCustomer', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                if (newValue) {
                    $scope.getCustomer(newValue);
                }
                if ((newValue != $scope.add_data.customer_name) && oldValue) {
                    if ($scope.add_data.risk_id) {
                        $('#add_data_customer_name3').val('');
                        setTimeout(function() { $('#add_data_customer_name3').trigger('blur'); });
                    } else {
                        $('#add_data_customer_name1').val('');
                        setTimeout(function() { $('#add_data_customer_name1').trigger('blur'); });
                    }
                }
            });

        })
        .directive('statusTrans', function() {
            return {
                restrict: 'A',
                template: "{{status}}",
                link: function(scope, element, attrs) {
                    if (attrs.status) {
                        var code = scope.$eval(attrs.status);
                        var Names = ['未处理', '处理中', '已处理', '挂起'];
                        scope.status = Names[code];
                    }
                }
            };
        })
        .directive('showDesc', function($filter) {
            return {
                restrict: 'A',
                template: "<div ng-if='fullshow==0' >{{showdesc}}</div>" +
                    "<div ng-if='fullshow==1'>{{showdesc}}...<a ng-click='more()' title='点击查看完成风险情况说明'><i class='big blue info circle icon'></i></a>",
                link: function(scope, element, attrs) {
                    if (attrs.description) {
                        scope.desc = attrs.description;
                        scope.showdesc = scope.desc.length > 20 ? $filter('limitTo')(scope.desc, 20) : scope.desc;
                        scope.fullshow = scope.desc.length > 20 ? 1 : 0;
                    }
                },
                controller: function($scope, $element, $rootScope) {
                    $scope.more = function() {
                        $rootScope.description = $scope.desc;
                        $('.ui.description.modal').modal({
                            inverted: true,
                            closable:false,
                            observeChanges: true,
                        }).modal('show');
                    }
                }
            };
        });

});